package com.yyx.app1.Data;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.yyx.app1.Data.DiagnosticTools.RemedyInfo0_SQLiteOperation;
import com.yyx.app1.Data.DiagnosticTools.RemedyInfo1_SQLiteOperation;
import com.yyx.app1.Data.Medication.MedicationFirstList_SQLiteOperation;
import com.yyx.app1.Data.Medication.MedicationSecondList_SQLiteOperation;
import com.yyx.app1.Data.Medication.Medication_SQLiteOperation;
import com.yyx.app1.Data.inconpatibility.TabooCompatible_SQLiteOperation;
import com.yyx.app1.MyApp;
import com.yyx.app1.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by yuexing on 2015/9/29.
 * 拼接路径 自行加/
 */
public class DataInit {
    private boolean istest;
    private Context context;
    private String DataBaseName;
    private String DataBasePath;
    private String DataBaseDirectory;
    private int SQLite_Resource = R.raw.cxlin;
    private String packageName;
    private String APP_Path;
    private String SD_Path;
    private String APP_Directory;
    private String SD_Directory;
    private String DB_MedicationTableName;
    private String DB_MedicationFirstListTableName;
    private String DB_MedicationSecondListTableName;
    private String DB_TabooCompatibleTableName;
    private String DB_RemedyInfoTableName;
    private String[] urls=new String[]{"medicine.txt","secondcolumns.txt","remedyInfo.txt","tabooCompatible.txt","medication_firstcolumns.txt"};
    private String rooturl="http://www.cxlin.com/html/android";
    private String portrait_URL_head = "http://www.cxlin.com/img_root/img_cuser";// 头像图片 + /id/imagename就是地址
    private String Question_URL_head = "http://drugs.cxlin.com/images";//http://drugs.cxlin.com/images/medicine.jpg
    private String ImagePath;
    public static String httpHead = "http://www.cxlin.com:8090/sys/appInterface/";

    public DataInit(Context context, boolean istest, String DataBaseName) {
        this.istest=istest;
        this.context = context;
        this.DataBaseName=DataBaseName;
        this.packageName=context.getPackageName();
        APP_Path = "/data/data/"+packageName+"/database/"+DataBaseName+".db";
        SD_Path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.cxlin.database/"+DataBaseName+".db";
        APP_Directory = "/data/data/"+packageName+"/database";
        SD_Directory = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.cxlin.database";
        DB_MedicationTableName = "medication";
        DB_MedicationFirstListTableName = "medication_first_list";
        DB_MedicationSecondListTableName = "medication_second_list";
        DB_TabooCompatibleTableName = "taboo_compatible";
        DB_RemedyInfoTableName = "remedy_info";
        if (istest)
        {
            DataBasePath = SD_Path;
            DataBaseDirectory=SD_Directory;
            ImagePath = SD_Directory+"/images";
        }
        else
        {
            DataBasePath = APP_Path;
            DataBaseDirectory=APP_Directory;
            ImagePath = "/data/data/"+packageName+"/images";
        }
        File destDir = new File(ImagePath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    public String getPortrait_Http(String idimageName)
    {
        String portraitPath = ImagePath + "/" + idimageName.replace("/","");
        if(!new WebOperation().downloadNet(portrait_URL_head+"/"+idimageName,portraitPath))
        {
            Log.i("正常1510201544","下载失败");
            return null;
        }
        else
        {
            return portraitPath;
        }
    }

    public String getQuestionImage_Http(String imageName)
    {
        String Path = ImagePath + "/" + imageName;
        if(!new WebOperation().downloadNet(Question_URL_head+"/"+imageName,Path))
        {
            Log.i("正常1510201545","下载失败");
            return null;
        }
        else
        {
            return Path;
        }
    }

    public Medication_SQLiteOperation getMedication_SQLiteOperation()
    {
        return new Medication_SQLiteOperation(this);
    }

    public MedicationFirstList_SQLiteOperation getMedicationFirstList_SQLiteOperation()
    {
        return new MedicationFirstList_SQLiteOperation(this);
    }

    public MedicationSecondList_SQLiteOperation getMedicationSecondList_SQLiteOperation()
    {
        return new MedicationSecondList_SQLiteOperation(this);
    }

    public TabooCompatible_SQLiteOperation getTabooCompatible_SQLiteOperation()
    {
        return new TabooCompatible_SQLiteOperation(this);
    }

    public RemedyInfo0_SQLiteOperation getRemedyInfo0_SQLiteOperation()
    {
        return new RemedyInfo0_SQLiteOperation(this);
    }

    public RemedyInfo1_SQLiteOperation getRemedyInfo1_SQLiteOperation()
    {
        return new RemedyInfo1_SQLiteOperation(this);
    }

    public void DeleteAll()
    {
        getMedication_SQLiteOperation().deleteAll();
        getMedicationFirstList_SQLiteOperation().deleteAll();
        getMedicationSecondList_SQLiteOperation().deleteAll();
        getTabooCompatible_SQLiteOperation().deleteAll();
        getRemedyInfo0_SQLiteOperation().deleteAll();
    }

    public void Download()
    {
        new WebOperation(rooturl,urls,DataBaseDirectory).Download();
    }

    public SQLiteDatabase creatOrOpenDatabase()
    {
        SQLiteDatabase db=null;
        try
        {
            File dbp=new File(DataBaseDirectory);
            File dbf=new File(DataBasePath);
            if(!dbp.exists())
            {
                dbp.mkdir();
            }
            //数据库文件是否创建成功
            boolean isFileCreateSuccess=false;
            if(!dbf.exists())
            {
                if (istest)
                {
                    isFileCreateSuccess=dbf.createNewFile();
                }
                else
                {
                    copyDataBase();
                }
            }
            else
            {
                isFileCreateSuccess=true;
            }
            if(isFileCreateSuccess)
                db = SQLiteDatabase.openOrCreateDatabase(dbf, null);
        }
        catch (Exception e)
        {
            Log.e("异常1510201351",e.toString());
        }
        finally
        {
            return db;
        }
    }

    public void createTable()
    {
        SQLiteDatabase db = creatOrOpenDatabase();
        try
        {
            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_MedicationTableName + " (number integer primary key ," +
                    "id varchar,"+//private String id;
                    "medicineName varchar,"+//private String medicineName;     //药品名字
                    "adminId integer,"+//private Integer adminId;         //管理员id
                    "medicineFactory varchar,"+//private String medicineFactory;  //生产厂家
                    "address varchar,"+//private String address;          //厂家地址
                    "belongToColumn integer,"+//private Integer belongToColumn;  //所属栏目
                    "explain varchar,"+//private String explain;          //补充说明
                    "medicineImage varchar,"+//private String medicineImage;    //药品图片
                    "addtime varchar,"+//private String addtime;          //时间
                    "pinyin varchar,"+//private String pinyin;           //汉语拼音
                    "englishName varchar,"+//private String englishName;      //英文名称
                    "petName varchar,"+//private String petName;          //别名
                    "medicineContent varchar,"+//private String medicineContent;  //主要成分
                    "shape varchar,"+//private String shape;            //性状
                    "preparation varchar,"+//private String preparation;      //制剂与规格
                    "functionDosage varchar,"+//private String functionDosage;   //用法用量
                    "cureFun varchar,"+//private String cureFun;          //药理作用
                    "drugInteraction varchar,"+//private String drugInteraction;  //药物相互作用
                    "indication varchar,"+//private String indication;       //适应症
                    "clinical varchar,"+//private String clinical;         //临床应用
                    "effect varchar,"+//private String effect;           //不良反应
                    "attention varchar,"+//private String attention;        //注意事项
                    "contraindication varchar,"+//private String contraindication; //禁忌症
                    "status integer,"+//private Integer status;           //状态   0：创建  1：上架   -1：下架
                    "onTime varchar,"+//private String onTime;            //上架时间
                    "offTime varchar,"+//private String offTime;           //下架时间
                    "firstId varchar,"+//private String firstId;            //关联一级栏目
                    "columnName varchar,"+//private String columnName;       //所属栏目名称
                    "firstUrl varchar,"+//private String firstUrl;       //一级栏目url
                    "secondUrl varchar"+//private String secondUrl;       //二级栏目url
                    ");");

            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_MedicationFirstListTableName + " (number integer primary key ," +
                    "id varchar ,"+//private String id;
                    "fcname varchar ,"+//private String fcname;         //栏目名称
                    "seoTitle varchar ,"+//private String seoTitle;       //SEO标题
                    "fcdescription varchar ,"+//private String fcdescription;  //SEO描述
                    "fckeyWord varchar ,"+//private String fckeyWord;      //SEO关键词
                    "modulesId integer ,"+//private Integer modulesId;     //栏目所属模块
                    "addTime varchar ,"+//private String addTime;        //创建时间
                    "orderby integer ,"+//private Integer orderby;       //排序顺序
                    "url varchar ,"+//private String url;            //路径
                    "urlrewrite varchar"+//private String urlrewrite;     //真实路径
                    ");");

            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_MedicationSecondListTableName + " (number integer primary key ," +
                    "id varchar ,"+//private String id;
                    "firstColumnId integer ,"+//private Long firstColumnId;    //关联一级栏目
                    "scname varchar ,"+//private String scname;         //栏目名称
                    "scdescription varchar ,"+//private String scdescription;  //SEO描述
                    "seoTitle varchar ,"+//private String seoTitle;       //SEO标题
                    "sckeyWord varchar ,"+//private String sckeyWord;      //SEO关键字
                    "addTime varchar ,"+//private String addTime;     //创建时间
                    "orderby integer ,"+//private Integer orderby;       //排序顺序
                    "modulesId integer ,"+//private Integer modulesId;     //栏目所属模块
                    "url varchar ,"+//private String url;            //路径
                    "urlrewrite varchar ,"+//private String urlrewrite;     //真实路径
                    "rolePower varchar ,"+//private String rolePower;     //角色权限:1表示普通用户；2表示医生
                    "firstColumnName varchar"+//private String firstColumnName;//栏目名称
                    ");");

            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_TabooCompatibleTableName + " (number integer primary key ," +
                    "id varchar ,"+//private String id;
                    "firstMedicine varchar ,"+//private String firstMedicine;  //主药品名
                    "secondMedicine varchar ,"+//private String secondMedicine; //从药品名
                    "effect varchar ,"+//private String effect;		   //作用机制
                    "tcproperty varchar ,"+//private String tcproperty;     //配伍属性
                    "releaseTime varchar ,"+//private String releaseTime;    //发布时间
                    "adminId varchar ,"+//private String adminId;        //管理员id
                    "status integer ,"+//private Integer status;  	   //状态   0：创建  1：上架   -1：下架
                    "onTime varchar ,"+//private String onTime;         //上架时间
                    "offTime varchar ,"+//private String offTime;        //下架时间
                    "startTime varchar ,"+//private String startTime;
                    "endTime varchar "+//private String endTime;
                    ");");

            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_RemedyInfoTableName + " (number integer primary key ," +
                    "id varchar ,"+//private String id;
                    "chineseName varchar ,"+//private String chineseName; // 中文名称
                    "curtailment varchar ,"+//private String curtailment; // 缩写
                    "position varchar ,"+//private String position;  // 产生部位
                    "summarize varchar ,"+//private String summarize;  // 概述
                    "highMean varchar ,"+//private String highMean; // 指标过高意义
                    "lowMean varchar ,"+//private String lowMean; //指标过低意义
                    "type varchar ,"+//private String type; // 工具
                    "createTime varchar "+//private String createTime; //时间
                    ");");
        }
        catch (Exception e)
        {
            Log.e("异常1510201352", e.toString());
        }

    }

    public void LoadData()
    {
        getTabooCompatible_SQLiteOperation().InjectionSQList();
        getMedication_SQLiteOperation().InjectionSQList();
        getMedicationFirstList_SQLiteOperation().InjectionSQList();
        getMedicationSecondList_SQLiteOperation().InjectionSQList();
        getRemedyInfo0_SQLiteOperation().InjectionSQList();
        Log.i("消息","LoadData结束");
    }

    public void DatabaseInit()
    {
        SQLiteDatabase db = creatOrOpenDatabase();
        if(db!=null)
        {
            db.close();
        }
    }

//    private String[] urls=new String[]{"medicine.txt","secondcolumns.txt","remedyInfo.txt","tabooCompatible.txt","medication_firstcolumns.txt"};//顺序不可改变
    public String getMedicationDataFileName()
    {
        return urls[0];
    }

    public String getMedicationFirstListDataFileName()
    {
        return urls[4];
    }

    public String getMedicationSecondListDataFileName()
    {
        return urls[1];
    }

    public String getTabooCompatibleDataFileName()
    {
        return urls[3];
    }

    public String getRemedyInfoFileName()
    {
        return urls[2];
    }

    public void upDataBase()
    {
    }

    /**
     * 判断数据库是否存在
     *
     * @return false or true
     */
    public boolean checkDataBase() {
        SQLiteDatabase db = null;
        try
        {
            db = SQLiteDatabase.openDatabase(DataBasePath, null,SQLiteDatabase.OPEN_READONLY);
            if (db != null)
            {
                db.close();
            }
        }
        catch (SQLiteException e)
        {
            Log.e("异常1511091711",e.toString());
        }
        finally
        {
            return db != null ? true : false;
        }
    }

    /**
     * 复制数据库到手机指定文件夹下
     *
     * @throws IOException
     */
    public boolean copyDataBase() {
        try
        {
            File dir = new File(DataBaseDirectory);
            if (!dir.exists())// 判断文件夹是否存在，不存在就新建一个
                dir.mkdir();
            FileOutputStream os = new FileOutputStream(DataBasePath);// 得到数据库文件的写入流
            InputStream is = context.getResources().openRawResource(SQLite_Resource);// 得到数据库文件的数据流
            byte[] buffer = new byte[1024*1024];
            int count = 0;
            while ((count = is.read(buffer)) > 0)
            {
                os.write(buffer, 0, count);
                os.flush();
            }
            is.close();
            os.close();
            return true;
        }
        catch (Exception e)
        {
            Log.e("异常", e.toString());
            return false;
        }
    }

    public String[] getUrls() {
        return urls;
    }

    public void setUrls(String[] urls) {
        this.urls = urls;
    }

    public String getRooturl() {
        return rooturl;
    }

    public void setRooturl(String rooturl) {
        this.rooturl = rooturl;
    }

    public String getDB_MedicationTableName() {
        return DB_MedicationTableName;
    }

    public void setDB_MedicationTableName(String DB_MedicationTableName) {
        this.DB_MedicationTableName = DB_MedicationTableName;
    }

    public String getDB_MedicationFirstListTableName() {
        return DB_MedicationFirstListTableName;
    }

    public void setDB_MedicationFirstListTableName(String DB_MedicationFirstListTableName) {
        this.DB_MedicationFirstListTableName = DB_MedicationFirstListTableName;
    }

    public String getDB_MedicationSecondListTableName() {
        return DB_MedicationSecondListTableName;
    }

    public void setDB_MedicationSecondListTableName(String DB_MedicationSecondListTableName) {
        this.DB_MedicationSecondListTableName = DB_MedicationSecondListTableName;
    }

    public String getDB_RemedyInfoTableName() {
        return DB_RemedyInfoTableName;
    }

    public void setDB_RemedyInfoTableName(String DB_RemedyInfoTableName) {
        this.DB_RemedyInfoTableName = DB_RemedyInfoTableName;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public String getDataBaseName() {
        return DataBaseName;
    }

    public void setDataBaseName(String dataBaseName) {
        DataBaseName = dataBaseName;
    }

    public String getDataBasePath() {
        return DataBasePath;
    }

    public void setDataBasePath(String dataBasePath) {
        DataBasePath = dataBasePath;
    }

    public String getDataBaseDirectory() {
        return DataBaseDirectory;
    }

    public void setDataBaseDirectory(String dataBaseDirectory) {
        DataBaseDirectory = dataBaseDirectory;
    }

    public int getSQLite_Resource() {
        return SQLite_Resource;
    }

    public void setSQLite_Resource(int SQLite_Resource) {
        this.SQLite_Resource = SQLite_Resource;
    }

    public String getPackageName() {
        return packageName;
    }

    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    public String getAPP_Path() {
        return APP_Path;
    }

    public void setAPP_Path(String APP_Path) {
        this.APP_Path = APP_Path;
    }

    public String getSD_Path() {
        return SD_Path;
    }

    public void setSD_Path(String SD_Path) {
        this.SD_Path = SD_Path;
    }

    public String getAPP_Directory() {
        return APP_Directory;
    }

    public void setAPP_Directory(String APP_Directory) {
        this.APP_Directory = APP_Directory;
    }

    public String getSD_Directory() {
        return SD_Directory;
    }

    public void setSD_Directory(String SD_Directory) {
        this.SD_Directory = SD_Directory;
    }

    public String getDB_TabooCompatibleTableName() {
        return DB_TabooCompatibleTableName;
    }

    public void setDB_TabooCompatibleTableName(String DB_TabooCompatibleTableName) {
        this.DB_TabooCompatibleTableName = DB_TabooCompatibleTableName;
    }

    public String getImagePath() {
        return ImagePath;
    }

    public void setImagePath(String imagePath) {
        ImagePath = imagePath;
    }

    public String getPortrait_URL_head() {
        return portrait_URL_head;
    }

    public void setPortrait_URL_head(String portrait_URL_head) {
        this.portrait_URL_head = portrait_URL_head;
    }

    public String getQuestion_URL_head() {
        return Question_URL_head;
    }

    public void setQuestion_URL_head(String question_URL_head) {
        Question_URL_head = question_URL_head;
    }

    public Bitmap loadLocalBitmap(String imageName) {
        try
        {
            if (imageName == null || imageName.isEmpty())
            {
                return null;
            }
            String path = ImagePath+"/"+imageName;
            //判断本地文件是否存在
            File file = new File(path);
            if (!file.exists())
            {
                return null;
            }
            FileInputStream fis = new FileInputStream(path);
            return BitmapFactory.decodeStream(fis);
        }
        catch (Exception e)
        {
            Log.e("异常1510201337",e.toString());
            return null;
        }
    }
}
